const wsConnection = {
  // url: 'ws://127.0.0.1:22225',
  $ws: null,
  lockReturn: false,
  timeout: 30 * 1000 * 5,
  timeoutObj: null,
  timeoutNum: null,
  serverTimeoutObj: null,
  // 初始化webSocket长连接
  initWebSocket:function(url){
    this.$ws = new WebSocket(url)
    this.$ws.onopen = this.wsOpen
    this.$ws.onclose = this.wsClose
    this.$ws.onmessage = this.wsMsg
    this.$ws.onerror = this.wsError
  },

  // 打开websocket
  wsOpen: function() {
    // 开始websocket心跳
    wsConnection.startWsHeartbeat()
    const data = JSON.stringify({'function':'Heartbeat'});
    wsConnection.wsSend(data)
  },

  // 关闭webSocket
  wsClose: function(e) {
    console.log(e, 'ws close')
  },

  
  // 发送消息
  wsSend: function(e) {
    // var data = JSON.stringify({ 'function': 'Heartbeat' });
    // const data = JSON.stringify({ 'function': 'releaseSocketPro' });
    // console.log(data, '发送数据')
    this.$ws.send(e)
  },

  // wsConnection.resetHeartbeat()
  wsMsg: function(msg) {
    // 每次接收到服务端消息后 重置websocket心跳
    // wsConnection.resetHeartbeat()
    var Obj = JSON.parse(msg.data.replace(/[\r\n]/g, ""));
    return Obj
    //通用回调处理函数 jsonObj
    // cameraProduceMessage(Obj);
  },

  // 长连接错误
  wsError: function(err) {
    console.error(err, 'ws error')
    // this.$message({
    //     type: 'error',
    //     message: '长连接错误'
    // })
    // alert('长连接错误')
    // wsConnection.reconnect()
  },

  reconnect: function() {
    const _this = this
    if (_this.lockReturn) {
      return
    }
    _this.lockReturn = true
    _this.timeoutNum && clearTimeout(_this.timeoutNum)
    _this.timeoutNum = setTimeout(function() {
      _this.initWebSocket()
      _this.lockReturn = false
    }, 3000)
  },
  
  startWsHeartbeat: function() {
    const _this = this
    _this.timeoutObj && clearTimeout(_this.timeoutObj)
    _this.serverTimeoutObj && clearTimeout(_this.serverTimeoutObj)
    _this.timeoutObj = setInterval(function() {
      // 判断websocket当前状态
      if (_this.$ws.readyState !== 1) {
        _this.reconnect()
      }
    }, _this.timeout)
  },

  // 重置websocket心跳
  resetHeartbeat: function() {
    const _this = this
    clearTimeout(_this.timeoutObj)
    clearTimeout(_this.serverTimeoutObj)
    _this.startWsHeartbeat()
  }
}

// 抛出websocket对象
export default wsConnection